import React, {useState,useEffect} from "react";
import {get, map, trim} from "lodash";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Checkbox from "antd/lib/checkbox";
import Row from "antd/lib/row";
import Col from "antd/lib/col";
import Select from "antd/lib/select";
import Button from "antd/lib/button";
import Divider from "antd/lib/divider";
import Input from "antd/lib/input";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {UserProfile} from "@/components/proptypes";
import Workflow_bill_state from "@/services/workflow_bill_state";
import CreateStateDialog from "@/components/workflow/StateDialog";
import notification from "@/services/notification";
import {useGroupItems}  from "@/services/group";
import {useStateItems,useUserItems,useColItems} from "@/services/workflow_state";
import {currentUser} from "@/services/auth";
import Workflow_state from "@/services/workflow_state";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
const { confirm } = Modal;

function CreateBill_stateDialog({ bill_state, dialog }) {
  const {userLoaded, userdata } = useUserItems('params');
  const {groupLoaded, groupdata } = useGroupItems('params');
  const {stateLoaded, statedata } = useStateItems(0);
  const {colLoaded, coldata } = useColItems('hr');
  const [dataLoaded, setDataLoaded] = useState(bill_state.id ===0 ? true : false);
  const [workflow_stateid, setworkflow_stateid] = useState("");
  const [doc_status, setdoc_status] = useState("");
  const [allow_user, setallow_user] = useState([]);
  const [allow_group, setallow_group] = useState([]);
  const [message, setMessage] = useState("");
  const [timelimit, settimelimit] = useState(0);
  const [colcontrol, setcolcontrol] = useState(false);
  const [allow_col, setallow_col] = useState([]);
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateBill_stateEnabled =useState(true);// policy.isAdmin() || policy.isDefault();

  useEffect(() => {
    if (bill_state.id === 0) return;
    let cancelLoading = false;
    if (!cancelLoading) {
      setworkflow_stateid(bill_state.workflow_stateid);
      setdoc_status(bill_state.doc_status);
      setallow_user(bill_state.allow_user);
      setallow_group(bill_state.allow_group);
      setMessage(bill_state.message);
      settimelimit(bill_state.timelimit);
      setcolcontrol(bill_state.colcontrol);
      setallow_col(bill_state.allow_col);
      setDataLoaded(true);
    }

    return () => {
      cancelLoading = true;
    };
  }, [bill_state]);

  function handlestateChange(event) {
    const value = trim(event);
    setworkflow_stateid(value);
    setIsValid(value !== "");
  }

  function handledoc_statusChange(event) {
    const value = trim(event);
    setdoc_status(value);
    setIsValid(workflow_stateid !== "");
  }
  function handletimelimitChange(event) {
    const value = event.target.value;
    settimelimit(value);
    setIsValid(workflow_stateid !== "");
  }
  function handlecolcontrolChange(event) {
    const value = event.target.checked;
    setcolcontrol(value);
    setIsValid(workflow_stateid !== "");
  }
  function handleallow_userChange(checkedValues) {
    setallow_user(checkedValues);
    setIsValid(workflow_stateid !== "");
    // setIsValid(workflow_stateid !== "" && checkedValues.length !== 0 && allow_group.length !== 0);
  }
  function handleallow_colChange(checkedValues) {
    setallow_col(checkedValues);
    setIsValid(workflow_stateid !== "");
  }
  function handleallow_groupChange(checkedValues) {
    setallow_group(checkedValues);
    setIsValid(workflow_stateid !== "");
    // setIsValid(workflow_stateid !== "" && checkedValues.length !== 0 && allow_user.length !== 0);
  }
   function handlemessageChange(event) {
    const value = trim(event.target.value);
    setMessage(value);
    setIsValid(workflow_stateid !== "");
  }
  function showCreateStateDialog(id){
    CreateStateDialog.showModal({state_id: id})
    .onClose((result = {}) => {
        if (result.success) {
        }
      }).onDismiss(() => {
      });
  };
  function handleDelete() {
    confirm({
      title: '确定删除状态?',
      icon: <WarningOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Workflow_state.delete({id: workflow_stateid}).then(()=>{
          notification.success("状态删除成功.");
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  function handleSubmit() {
    setSaveInProgress(true);
    let a_cols=allow_col;
    if (!colcontrol){
      a_cols=[];
    }
    let params={
      id: bill_state.id,
      userid: currentUser.id,
      workflowid: bill_state.workflowid,
      workflow_stateid: workflow_stateid,
      doc_status: doc_status,
      allow_user: allow_user,
      allow_group: allow_group,
      message: message,
      colcontrol: colcontrol,
      timelimit: timelimit,
      allow_col: a_cols,
    }
    if (bill_state.id === 0) {
      Workflow_bill_state.create(params)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    } else {
      Workflow_bill_state.save(params)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateBill_stateEnabled ? {} : { footer: null })}
      title="流程状态"
      width={document.querySelector('body').offsetWidth*0.7}
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled:  !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateBill_stateDialogExtra" disabled={!isCreateBill_stateEnabled}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
         <Row>
				  <Col span={10}>
            {stateLoaded && (
            <Form.Item style={{ marginBottom: 5 }} label="状态">
              <Select 
                showSearch
                optionFilterProp="children"
                style={{ width:  300 }} 
                defaultValue={workflow_stateid} 
                onChange={handlestateChange} 
                disabled={saveInProgress} 
                >
                {map(statedata, ds => (
                  <Select.Option key={ds.id} value={ds.id}>{ds.name}</Select.Option>
                ))}
              </Select>
            </Form.Item>
            )}
				  </Col>
				  <Col span={10}>
            <Button type="primary" onClick={() => showCreateStateDialog(0)}>
              <i className="fa fa-plus m-r-5" />
              新建
            </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => showCreateStateDialog(workflow_stateid)} >
            <i className="fa fa-save m-r-5" />
            修改
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => handleDelete()} >
            <i className="fa fa-trash m-r-5" />
            删除
          </Button>
				  </Col>
        </Row>
       <Row>
        <Col span={10}>
        <Form.Item style={{ marginBottom: 5 }} label="状态字段">
              <Select style={{ width:  300 }} defaultValue={doc_status} onChange={handledoc_statusChange} disabled={saveInProgress}>
                <Select.Option key="0" value="0">草稿</Select.Option>
                <Select.Option key="1" value="1">审核中</Select.Option>
                <Select.Option key="2" value="2">已审核</Select.Option>
              </Select>
        </Form.Item>
        </Col>
        <Col span={10}>
        <Form.Item style={{ marginBottom: 5 }} label="审批期限">
              <Input
                value={timelimit}
                onChange={handletimelimitChange}
                placeholder="天数"
                onkeyup="this.value=this.value.replace(/\D/g,'')"
                onafterpaste="this.value=this.value.replace(/\D/g,'')"
                type="number"
                disabled ={saveInProgress}
              />
        </Form.Item>
        </Col>
      </Row>
       <Row>
        <Col span={10}>
          <p>允许编辑</p>
        </Col>
      </Row>
       <Row>
        <Col span={10}>
        {userLoaded && (
        <Form.Item style={{ marginBottom: 5 }} label="用户">
        <Checkbox.Group
          loading={!userLoaded}
          defaultValue={allow_user}
          onChange={handleallow_userChange}>
          <Row>
          {map(userdata, ds => (
            <Col span={8}><Checkbox value={ds.id}>{ds.name}</Checkbox></Col>
          ))}
          </Row>
        </Checkbox.Group>
        </Form.Item>
        )}
        </Col>
        <Col span={10}>
        {groupLoaded && (
        <Form.Item style={{ marginBottom: 5 }} label="权限组">
        <Checkbox.Group
          loading={!groupLoaded}
          defaultValue={allow_group}
          onChange={handleallow_groupChange}>
          <Row>
          {map(groupdata, ds => (
            <Col span={8}><Checkbox value={ds.id}>{ds.name}</Checkbox></Col>
          ))}
          </Row>
        </Checkbox.Group>
        </Form.Item>
        )}
        </Col>
      </Row>
      <Row>
        <Col span={10}>
          <Form.Item style={{ marginBottom: 5 }} label="编辑字段">
           <Checkbox checked={colcontrol} onChange={handlecolcontrolChange}></Checkbox>
          </Form.Item>
        </Col>
      </Row>
       <Row>
        <Col span={20}>
        {colLoaded && colcontrol && (
        <Form.Item style={{ marginBottom: 5 }}>
        <Checkbox.Group
          loading={!colLoaded}
          defaultValue={allow_col}
          onChange={handleallow_colChange}>
          <Row>
          {map(coldata, ds => (
            <Col span={6}><Checkbox value={ds.code}>{ds.name}</Checkbox></Col>
          ))}
          </Row>
        </Checkbox.Group>
        </Form.Item>
        )}
        </Col>
      </Row>
        <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="信息">
              <textarea
                rows="5" cols="100"
                textAlignVertical="top"
                height="100px"
                defaultValue={message}
                onChange={handlemessageChange}
                placeholder="信息"
                disabled={saveInProgress}
              />
						</Form.Item>
				  </Col>
        </Row>
      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateBill_stateDialog.propTypes = {
  bill_state: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateBill_stateDialog);
